package com.jian.channel;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author Jiange
 * @create 2021-09-11-16:03
 */
public class ServerSocketChannelTest {
    public static void main(String[] args) throws Exception {
        //本身不进行数据的传输，是一个基于通道的socket的监听器，监听传入里面的连接  包括创建新的SocketChannel

        int port = 8888;
        ByteBuffer buffer = ByteBuffer.wrap("建哥最帅".getBytes());
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(port));

        //可以设置成非阻塞
        ssc.configureBlocking(false);  //非阻塞

        //监听是否有新的连接传入
        while(true){
            SocketChannel sc = ssc.accept();//在非阻塞的状态下会 一直阻塞等待连接
            if(sc != null){
                System.out.println(sc.socket().getInetAddress());
                buffer.rewind();//将指针指向0
                sc.write(buffer);
                sc.close();
            }else{
                System.out.println("正在等待-----");
                Thread.sleep(2000);
            }

        }
    }
}
